using System;
using Gj;
using UnityEngine;
using UnityEngine.UI;

public class ProgressHelper : NodeHelper
{
    public enum ProgressValueType
    {
        Hundred,
        One,
        None,
    }
    

    public Image Bar;
    public Slider Slider;
    public ProgressTextHelper ProgressText;
    public TextHelper Text;
    public bool anim;
    public float time;
    public EaseType easeType = EaseType.linear;
    public ProgressValueType type = ProgressValueType.Hundred;
    public AudioClip clip;
    public SoundType soundType;
    private bool animing;
    private float currentTime;
    private float currentValue;
    private float endTime;
    private float startTime;
    private float value;

    protected override BindDataType bindDataType => BindDataType.Float;

    private void Update()
    {
        if (!animing) return;

        if (currentValue == 1)
        {
            animing = false;
            Emit(UIEvent.End);
            if (soundType != SoundType.None)
                Game.single.PlayEFF(soundType);
            else if (clip != null) Game.single.PlayEFF(clip);
            return;
        }
        currentTime += Time.deltaTime;
        currentValue =  MathTools.Compute(easeType, 0, 1, (currentTime - startTime) / (endTime - startTime));
        RefreshData(currentValue);
    }

    protected override void BindData(float f)
    {
        if (value == f) return;
        if (!anim)
        {
            RefreshData(f);
        }
        else if (f > 0)
        {
            value = f;
            startTime = Time.time;
            currentTime = Time.time;
            endTime = f;
            animing = true;
            currentValue = 0;
            RefreshData(0);
        }
    }

    private void RefreshData(float f)
    {
        switch (type)
        {
            case ProgressValueType.Hundred:
                f = (float)Math.Round(f / 100, 2);
                break;
            case ProgressValueType.One:
                f = (float)Math.Round(f, 2);
                break;
        }
        if (Slider != null) Slider.value = f;
        if (Bar != null) Bar.fillAmount = f;
        if (ProgressText != null) ProgressText.SetProgress(f);
        if (Text != null) Text.SetData((f * 100).ToString());
    }
}